interface IPageData {
  favoriteList: Array<{
    id: number;
    title: string;
    imageUrl: string;
    favoriteTime: string;
  }>;
}

Page<IPageData>({
  data: {
    favoriteList: []
  },

  onLoad() {
    // 页面加载时的初始化逻辑
    this.fetchFavoriteList();
  },

  async fetchFavoriteList() {
    const userId = wx.getStorageSync('userId');
    try {
      const response = await new Promise((resolve, reject) => wx.request({
        url: 'https://fairy.ymdx.cn/v1/fairy/collectList',
        method: 'POST',
        data: { userId },
        success: function(res) {
          resolve(res);
        },
        fail: function(err) {
          reject(err);
        }
      }));

      if (response.data && response.data.code === 200) {
        const favoriteList = response.data.data.map(item => ({
          id: item.id,
          title: item.name,
          imageUrl: item.thumbnail,
          favoriteTime: item.createTime.split(' ')[0]
        }));
        this.setData({ favoriteList });
      } else {
        throw new Error(response.data?.msg || '获取收藏列表失败');
      }
    } catch (error) {
      console.error('获取收藏列表失败:', error);
      wx.showToast({
        title: '获取收藏列表失败',
        icon: 'error'
      });
    }
  },

  readStory(event: WechatMiniprogram.TouchEvent) {
    const storyId = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/story/story?id=${storyId}`
    });
  },

  async cancelFavorite(event: WechatMiniprogram.TouchEvent) {
    const storyId = event.currentTarget.dataset.id;
    wx.showModal({
      title: '取消收藏',
      content: '确定要取消收藏这个故事吗？',
      success: async (res) => {
        if (res.confirm) {
          const userId = wx.getStorageSync('userId');
          try {
            const response = await new Promise((resolve, reject) => wx.request({
              url: 'https://fairy.ymdx.cn/v1/fairy/toggleCollect',
              method: 'POST',
              data: { userId, detailId: storyId },
              success: function(res) {
                resolve(res);
              },
              fail: function(err) {
                reject(err);
              }
            }));

            if (response.data && response.data.code === 200) {
              const newList = this.data.favoriteList.filter(item => item.id !== storyId);
              this.setData({ favoriteList: newList });
              wx.showToast({
                title: '已取消收藏',
                icon: 'success'
              });
            } else {
              throw new Error(response.data?.msg || '取消收藏失败');
            }
          } catch (error) {
            console.error('取消收藏失败:', error);
            wx.showToast({
              title: '取消收藏失败',
              icon: 'error'
            });
          }
        }
      }
    });
  },

  goToHome() {
    wx.switchTab({
      url: '/pages/home/home'
    });
  },

  onPullDownRefresh() {
    // 下拉刷新
    this.fetchFavoriteList();
    wx.stopPullDownRefresh();
  },

  onShareAppMessage() {
    return {
      title: '童话大全 - 我的收藏',
      path: '/pages/favorite/favorite'
    };
  }
});